package ru.aslanov.schedule.server.services;

import ru.aslanov.schedule.model.DataItem;
import ru.aslanov.schedule.model.GCalendar;
import ru.aslanov.schedule.model.Group;
import ru.aslanov.schedule.model.Operation;
import ru.aslanov.schedule.server.AccessDeniedException;
import ru.aslanov.schedule.server.AccessManager;
import ru.aslanov.schedule.server.BackReference;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 27, 2010 4:00:59 PM
 *
 * @author Sergey Aslanov
 */
public class GCalendarService extends ScheduleChildService<GCalendar>{
    public GCalendarService() {
        super("name");
        addBackRef(new BackReference(Group.class, "calendarKey"));
    }

    @Override
    protected void fillDataItem(DataItem dataItem, GCalendar object, HttpServletRequest request, PersistenceManager pm) throws Exception {
        super.fillDataItem(dataItem, object, request, pm);
        setAttr(dataItem, "calendarId", object.getCalendarId());
        setAttr(dataItem, "name", object.getName());
    }

    @Override
    protected void makeObjectPersistent(PersistenceManager pm, GCalendar object, HttpServletRequest request) {
        getParent(pm, request).getCalendars().add(object);
    }

    @Override
    protected Class<GCalendar> getEntityClass() {
        return GCalendar.class;
    }

    @Override
    protected boolean checkPermission(GCalendar existingEntity, HttpServletRequest request, PersistenceManager pm, Operation operation) throws AccessDeniedException {
        String scheduleKey = existingEntity != null ? existingEntity.getSchedule().getEncodedKey() : getParentKey(request);

        AccessManager am = AccessManager.getInstance();
        return am.hasAccessToSchedule(scheduleKey, operation == Operation.VIEW ? Operation.VIEW : Operation.UPDATE);
    }


}
